package com.example.mybatisplusdemo.controller;

import com.example.mybatisplusdemo.dao.UserMapper;
import com.example.mybatisplusdemo.entity.UserEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * @author H
 * @date 2022/12/10
 */
@RestController
@RequiredArgsConstructor
public class UserController implements ApplicationContextAware {

    private final UserMapper userMapper;
    // @Autowired
    // private UserController userController;
    private ApplicationContext applicationContext;

    @Transactional
    @GetMapping("saveUser")
    public String saveUser() {
        UserEntity userEntity = new UserEntity().setUsername("小花").setHobby(Arrays.asList(1,5,8)).setGender(1).setAge(21);
        userMapper.insert(userEntity);
        UserEntity userEntity1 = new UserEntity().setUsername("小花1").setHobby(Arrays.asList(1,5,8)).setGender(1).setAge(21);

        // 从IOC容器中取出代理对象
        UserController userController = applicationContext.getBean(UserController.class);
        userController.insertUser(userEntity1);
        int a = 10 / 0;
        return "success";
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void insertUser(UserEntity user) {
        userMapper.insert(user);
        userMapper.insert(user);
    }

    @GetMapping("getUser")
    public String getUser() {
        List<UserEntity> userEntities = userMapper.selectList(null);
        userEntities.forEach(System.out::println);
        return "success";
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
